<template>
	<view class="container">
		<!-- 任务名称 -->
		<view class="form-item">
			<text class="label">任务名称<text class="required">*</text></text>
			<input class="input" type="text" v-model="formData.taskName" placeholder="请输入任务名称"
				@input="validateTaskName" />
			<text v-if="errors.taskName" class="error-text">{{errors.taskName}}</text>
		</view>

		<!-- 任务描述 -->
		<view class="form-item">
			<text class="label">任务描述</text>
			<textarea class="textarea" v-model="formData.description" placeholder="请输入任务描述" />
		</view>

		<!-- 任务期限 -->
		<view class="form-item">
			<text class="label">任务期限<text class="required">*</text></text>
			<view class="date-picker" @tap="showDatePicker">
				<text>{{formData.dueDate
				 || '请选择日期'}}</text>
				<text class="calendar-icon">📅</text>
			</view>
			<text v-if="errors.dueDate" class="error-text">{{errors.dueDate}}</text>
		</view>

		<!-- 负责人 -->
		<view class="form-item">
			<view class="label-container">
				<text class="label">负责人<text class="required">*</text></text>
				<button class="add-btn" @tap="showAssigneeSelector">+</button>
			</view>
			<view class="assignee-container">
				<view v-for="(assignee, index) in selectedAssignees" :key="index" class="assignee-tag">
					<text>{{assignee.nickname}}</text>
					<text class="delete-icon" @tap="removeAssignee(assignee.userId)">×</text>
				</view>
			</view>
			<text v-if="errors.assignees" class="error-text">{{errors.assignees}}</text>
		</view>

		<!-- 父任务 -->
		<view class="form-item">
			<text class="label">父任务</text>
			<view class="select-box" @tap="showParentTaskPicker">
				<text>{{selectedParentTask ? selectedParentTask.taskName : '选择父任务'}}</text>
				<text class="arrow-icon">▼</text>
			</view>
		</view>

		<!-- 子任务 -->
		<view class="form-item">
			<text class="label">子任务</text>
			<view class="select-box" @tap="showChildTasksPicker">
				<text>{{selectedChildTasksText}}</text>
				<text class="arrow-icon">▼</text>
			</view>
		</view>

		<!-- 提交按钮 -->
		<button class="submit-btn" @tap="handleSubmit">创建任务</button>

		<!-- 日期选择器弹窗 -->
		<uni-calendar ref="calendar" :insert="false" :start-date="startDate" :end-date="endDate"
			@confirm="onSelectDate" />

		<!-- 负责人选择弹窗 -->
		<uni-popup ref="assigneePopup" type="bottom">
			<view class="popup-content">
				<view class="popup-header">
					<text>选择负责人</text>
					<text @tap="hideAssigneeSelector" class="close-icon">×</text>
				</view>
				<view class="popup-body">
					<checkbox-group @change="onAssigneeSelect">
						<label v-for="user in availableUsers" :key="user.userId" class="checkbox-item">
							<checkbox :value="user.userId" :checked="isUserSelected(user.userId)" color="#2979ff" />
							<text class="checkbox-label">{{user.nickname}}</text>
						</label>
					</checkbox-group>
				</view>
			</view>
		</uni-popup>

		<!-- 父任务选择器弹窗 -->
		<uni-popup ref="parentTaskPopup" type="bottom">
			<view class="popup-content">
				<view class="popup-header">
					<text>选择父任务</text>
					<text @tap="hideParentTaskPicker" class="close-icon">×</text>
				</view>
				<view class="popup-body">
					<view class="task-list">
						<view v-for="task in parentTasks" :key="task.taskId" class="task-item"
							:class="{'task-item--selected': task.taskId === pId}" @tap="onParentTaskSelect(task)">
							<text class="task-label">{{task.taskName}}</text>
							<text v-if="task.taskId === pId" class="selected-icon">✓</text>
						</view>
					</view>
				</view>
			</view>
		</uni-popup>

		<!-- 子任务选择器弹窗 -->
		<uni-popup ref="childTasksPopup" type="bottom">
			<view class="popup-content">
				<view class="popup-header">
					<text>选择子任务</text>
					<text @tap="hideChildTasksPicker" class="close-icon">×</text>
				</view>
				<view class="popup-body">
					<view class="task-list">
						<view v-for="task in childTasks" :key="task.taskId" class="task-item" :class="{
		                        'task-item--selected': childTaskIds.includes(task.taskId),
		                        'task-item--disabled': task.taskId === pId
		                    }" @tap="onChildTaskSelect(task)">
							<text class="task-label">{{task.taskName}}</text>
							<text v-if="childTaskIds.includes(task.taskId)" class="selected-icon">✓</text>
						</view>
					</view>
				</view>
			</view>
		</uni-popup>
	</view>
</template>

<script>
	import api from '@/api/api.js'
	export default {
		data() {
			return {
				taskState: {
					selectedParentId: null,
					selectedChildIds: []
				},
				endData: null,
				formData: {
					taskName: '',
					description: '',
					projectId: null,
					dueDate: '',
					status: '110',
				},
				taskId: -1,
				pId: -1,
				childTaskIds: [],
				assigneeIds: [],
				errors: {},
				parentTasks: [],
				childTasks: [],
				users: [],
				teamId: null,
				originChild: null,
				originUsers: null
			}
		},
		onLoad(options) {
			console.log(options)
			this.formData.projectId = options.projectId
			this.endDate = options.endDate
			if (options.editOrCreate === 'edit') {
				this.formData.taskName = options.taskName
				this.taskId = Number(options.taskId)
				this.formData.description = options.description
				this.formData.dueDate = options.dueDate
				if (options.pid && options.pid !== 'null') {
					this.pId = Number(options.pid)
					console.log(this.pId)
				}
				api.getCurrentSons({
					taskId: options.taskId
				}).then(re => {
					const origin = re.data.data
					this.originChild = origin.map(item => item.taskId)
					this.childTaskIds = origin.map(item => item.taskId)
				})
				api.getTaskUsers({
					taskId: options.taskId
				}).then(re => {
					this.originUsers = re.data.data
					this.assigneeIds = re.data.data.map(item => item.userId)
				})
			}
		},
		onShow: function(options) {
			this.teamId = wx.getStorageSync('TheChoosenTeam').teamId
			api.getAllParentTask({
				projectid: this.formData.projectId,
				taskId: this.taskId
			}).then(re => {
				const data = re.data.data
				this.parentTasks = data
			})
			api.getAllSonTask({
				projectid: this.formData.projectId,
				taskId: this.taskId
			}).then(re => {
				const data = re.data.data
				this.childTasks = data
			})
			api.getAllUsers({
				teamid: this.teamId
			}).then(re => {
				const data = re.data.data
				this.users = data
			})
		},
		computed: {
			startDate() {
				// 修改为当前日期
				const today = new Date()
				return this.formatDate(today)
			},
			selectedParentTask() {
				return this.parentTasks.find(task => task.taskId === this.pId)
			},
			selectedChildTasksText() {
				const count = this.childTaskIds.length
				return count > 0 ? `已选择 ${count} 项` : '选择子任务'
			},
			selectedAssignees() {
				return this.assigneeIds.map(id =>
					this.users.find(user => user.userId === id)
				).filter(Boolean)
			},
			availableUsers() {
				return this.users
			},
			// 过滤掉已选为子任务的选项
			availableParentTasks() {
				return this.parentTasks.filter(task =>
					!this.childTaskIds.includes(task.taskId)
				)
			},
			// 过滤掉已选为父任务的选项
			availableChildTasks() {
				return this.childTasks.filter(task =>
					task.taskId !== this.pId
				)
			}
		},
		methods: {
			formatDate(date) {
				const year = date.getFullYear()
				const month = String(date.getMonth() + 1).padStart(2, '0')
				const day = String(date.getDate()).padStart(2, '0')
				return `${year}-${month}-${day}`
			},
			validateTaskName() {
				if (!this.formData.taskName) {
					this.errors.taskName = '任务名称不能为空'
				} else if (this.formData.taskName.length > 50) {
					this.errors.taskName = '任务名称不能超过50个字符'
				} else {
					delete this.errors.taskName
				}
			},
			// 修改日期选择器的打开方法
			showDatePicker() {
				if (this.$refs.calendar) {
					this.$refs.calendar.open()
				}
			},

			// 修改日期选择确认方法
			onSelectDate(e) {
				if (e.fulldate) {
					console.log(e.fulldate)
					this.formData.dueDate = e.fulldate
				
				    }
				 if (e.fulldate) {
				        console.log(e.fulldate)
				        this.formData.dueDate = e.fulldate
				        // 添加这一行来清除错误提示
				        delete this.errors.dueDate
				    }
			},
			showAssigneeSelector() {
				this.$refs.assigneePopup.open()
			},
			hideAssigneeSelector() {
				this.$refs.assigneePopup.close()
			},
			onAssigneeSelect(e) {
				this.assigneeIds = e.detail.value.map(id => parseInt(id)) // 确保转换为数字类型
				if (this.assigneeIds.length > 0) {
					delete this.errors.assignees
				}
			},
			isUserSelected(userId) {
				return this.assigneeIds.includes(userId)
			},
			removeAssignee(userId) {
				this.assigneeIds = this.assigneeIds.filter(
					assigneeId => assigneeId !== userId
				)
				if (this.assigneeIds.length === 0) {
					this.errors.assignees = '请至少选择一个负责人'
				}
			},
			showParentTaskPicker() {
				this.$refs.parentTaskPopup.open()
			},
			hideParentTaskPicker() {
				this.$refs.parentTaskPopup.close()
			},
			onParentTaskSelect(task) {
				// 检查是否已经选择了子任务
				if (this.childTaskIds.length > 0) {
					uni.showToast({
						title: '已选择子任务,不能选择父任务',
						icon: 'none'
					});
					return;
				}

				// 如果点击的是已选中的任务,则取消选择
				if (this.pId === task.taskId) {
					this.pId = -1; // 改用 -1 作为取消选择的值
				} else {
					// 检查所选任务是否在子任务中
					if (this.childTaskIds.includes(task.taskId)) {
						// 如果任务已经是子任务，显示提示并返回
						uni.showToast({
							title: '该任务已被选为子任务',
							icon: 'none'
						});
						return;
					}
					// 否则选中新的任务
					this.pId = task.taskId;
				}
				this.hideParentTaskPicker();
			},

			onChildTaskSelect(task) {
				const taskId = task.taskId;

				// 检查是否已选择父任务
				if (this.pId !== -1) {
					uni.showToast({
						title: '已选择父任务,不能选择子任务',
						icon: 'none'
					});
					return;
				}

				// 检查是否是当前父任务
				if (taskId === this.pId) {
					uni.showToast({
						title: '该任务已被选为父任务',
						icon: 'none'
					});
					return;
				}

				// 切换选中状态
				const index = this.childTaskIds.indexOf(taskId);
				if (index === -1) {
					// 添加选中
					this.childTaskIds.push(taskId);
				} else {
					// 取消选中 
					this.childTaskIds.splice(index, 1);
				}
			},
			showChildTasksPicker() {
				this.$refs.childTasksPopup.open()
			},
			hideChildTasksPicker() {
				this.$refs.childTasksPopup.close()
			},

			// 修改表单验证方法
			validateForm() {
				this.validateTaskName()

				if (!this.formData.dueDate) {
					this.errors.dueDate = '请选择截止日期'
				}

				if (this.assigneeIds.length === 0) {
					this.errors.assignees = '请选择至少一个负责人'
				}

				return Object.keys(this.errors).length === 0
			},
			// 发送任务通知
			async sendTaskNotifications(taskId, assigneeIds, taskInfo) {
				const messageTitle = '任务提示';
				const messageNote =
					`任务名称：${taskInfo.taskName}\n任务描述：${taskInfo.description}\n截止日期：${taskInfo.dueDate}`;

				const promises = assigneeIds.map(assigneeId => {
					const message = {
						title: messageTitle,
						note: messageNote,
						userId: assigneeId
					};
					return api.sendMessage(message);
				});

				try {
					await Promise.all(promises);
					console.log('所有通知发送完成');
				} catch (error) {
					console.error('发送通知失败:', error);
					throw error;
				}
			},
			// 处理用户关系变更
			async handleUserRelationships(taskId, currentUsers, originalUsers) {
				// 找出需要删除和新增的用户
				const usersToRemove = originalUsers?.filter(user =>
					!currentUsers.includes(user.userId)
				) || [];

				const usersToAdd = currentUsers.filter(userId =>
					!originalUsers?.some(user => user.userId === userId)
				) || [];

				// 删除被取消的负责人
				if (usersToRemove.length > 0) {
					try {
						await api.removeTaskUsers(JSON.stringify({
							taskId: taskId,
							userIds: usersToRemove.map(user => user.userId)
						}));
					} catch (error) {
						console.error('删除用户关系失败:', error);
						throw error;
					}
				}

				// 添加新增的负责人
				if (usersToAdd.length > 0) {
					const userTaskList = usersToAdd.map(userId => ({
						userId: userId,
						taskId: taskId
					}));
					try {
						await api.saveUserTaskRelationship(JSON.stringify(userTaskList));
					} catch (error) {
						console.error('添加用户关系失败:', error);
						throw error;
					}
				}
			},

			async handleSubmit() {
				if (!this.validateForm()) {
					uni.showToast({
						title: '请检查表单填写',
						icon: 'none'
					});
					return;
				}

				try {
					var taskData;
					// 准备任务数据
					if (this.pId && this.pId > 0) {
						taskData = {
							...this.formData,
							pId: this.pId
						};
					} else {
						taskData = {
							...this.formData
						};
					}

					let taskId;

					// 判断是创建还是编辑任务
					if (this.taskId < 0) {
						// 创建新任务
						const response = await api.insertTask(taskData);
						taskId = response.data.data;

						// 处理新任务的用户关系
						await this.handleUserRelationships(taskId, this.assigneeIds, []);

						// 处理新任务的子任务关系
						if (this.childTaskIds.length > 0) {
							await this.handleChildTaskRelationships(taskId, this.childTaskIds, []);
						}
					} else {
						// 编辑现有任务
						taskId = this.taskId;
						taskData = {
							...taskData,
							taskId: taskId
						}
						await api.updateTask(taskData);

						// 处理用户关系变更
						await this.handleUserRelationships(taskId, this.assigneeIds, this.originUsers);

						// 处理子任务关系变更
						await this.handleChildTaskRelationships(taskId, this.childTaskIds, this.originChild);
					}

					// 发送任务通知
					await this.sendTaskNotifications(taskId, this.assigneeIds, taskData);

					// 显示成功提示
					uni.showToast({
						title: '操作成功',
						icon: 'success'
					});

					// 跳转到任务列表页面
					uni.navigateTo({
						url: `/pages/digest_test/digest_test?projectId=${this.formData.projectId}`
					});

				} catch (error) {
					console.error('提交失败:', error);
					uni.showToast({
						title: '操作失败，请重试',
						icon: 'none'
					});
				}
			},
			// 处理子任务关系变更
			async handleChildTaskRelationships(taskId, currentChildIds, originalChildIds) {
				// 找出需要移除和新增的子任务
				const childrenToRemove = originalChildIds?.filter(id =>
					!currentChildIds.includes(id)
				) || [];

				const childrenToAdd = currentChildIds.filter(id =>
					!originalChildIds?.includes(id)
				) || [];

				// 移除被取消的子任务关系
				if (childrenToRemove.length > 0) {
					try {
						await api.handleSonTasks({
							sonsId: childrenToRemove
						});
					} catch (error) {
						console.error('移除子任务关系失败:', error);
						throw error;
					}
				}

				// 添加新的子任务关系
				if (childrenToAdd.length > 0) {
					try {
						await api.handleSonTasks(JSON.stringify({
							sonsId: childrenToAdd,
							taskId: taskId
						}));
					} catch (error) {
						console.error('添加子任务关系失败:', error);
						throw error;
					}
				}
			},
		}
	}
</script>
<style lang="scss">
	.container {
		padding: 40rpx;
		min-height: 100vh;
		box-sizing: border-box;
		background-color: #f5f7fa;
	}

	.form-item {
		margin-bottom: 40rpx;
		background: #fff;
		padding: 30rpx 30rpx;
		border-radius: 16rpx;
		box-shadow: 0 2rpx 12rpx rgba(0, 0, 0, 0.05);
		position: relative;

		.label-container {
			display: flex;
			align-items: center;
			justify-content: space-between; // 添加这行来使加号按钮靠右
			margin-bottom: 16rpx;
			padding-right: 30rpx;

			.add-btn {
				width: 48rpx;
				height: 48rpx;
				line-height: 44rpx;
				padding: 0;
				font-size: 32rpx;
				border-radius: 24rpx;
				background-color: #2979ff;
				color: #fff;
				position: absolute;
				right: 30rpx;
				top: 30rpx;
			}
		}
	}

	.label {
		font-size: 30rpx;
		color: #1a1a1a;
		margin-bottom: 12rpx;
		display: block;
		font-weight: 500;

		.required {
			color: #ff4d4f;
			margin-left: 8rpx;
			font-weight: bold;
		}
	}

	.input {
		width: 100%;
		height: 88rpx;
		padding: 0 24rpx;
		font-size: 28rpx;
		border: 2rpx solid #e4e7ed;
		border-radius: 12rpx;
		background-color: #fff;
		box-sizing: border-box;
	}

	.textarea {
		width: 100%;
		height: 180rpx;
		padding: 24rpx;
		font-size: 28rpx;
		border: 2rpx solid #e4e7ed;
		border-radius: 12rpx;
		background-color: #fff;
		box-sizing: border-box;
	}

	.error-text {
		font-size: 24rpx;
		color: #ff4d4f;
		margin-top: 8rpx;
		display: flex;
		align-items: center;

		&::before {
			content: "!";
			display: inline-block;
			width: 28rpx;
			height: 28rpx;
			line-height: 28rpx;
			text-align: center;
			background: #fff2f0;
			border-radius: 50%;
			margin-right: 8rpx;
			border: 2rpx solid #ffccc7;
			color: #ff4d4f;
			font-size: 20rpx;
			font-weight: bold;
		}
	}

	.date-picker,
	.select-box {
		width: 100%;
		height: 88rpx;
		padding: 0 24rpx;
		display: flex;
		align-items: center;
		justify-content: space-between;
		border: 2rpx solid #e4e7ed;
		border-radius: 12rpx;
		background-color: #fff;
		box-sizing: border-box;

		.calendar-icon,
		.arrow-icon {
			color: #909399;
			font-size: 28rpx;
			margin-left: 16rpx;
		}
	}

	.assignee-container {
		display: flex;
		flex-wrap: wrap;
		gap: 16rpx;
		margin-top: 16rpx;

		.assignee-tag {
			display: flex;
			align-items: center;
			padding: 12rpx 20rpx;
			background-color: #ecf5ff;
			border-radius: 32rpx;

			text {
				color: #2979ff;
				font-size: 26rpx;
			}

			.delete-icon {
				margin-left: 12rpx;
				color: #2979ff;
				font-size: 32rpx;
			}
		}
	}

	.popup-content {
		background-color: #fff;
		border-radius: 24rpx 24rpx 0 0;
		padding: 40rpx 30rpx;

		.popup-header {
			display: flex;
			justify-content: space-between;
			align-items: center;
			margin-bottom: 30rpx;
			padding-bottom: 20rpx;
			border-bottom: 2rpx solid #f0f0f0;

			text {
				font-size: 34rpx;
				font-weight: 600;
				color: #1a1a1a;
			}

			.close-icon {
				color: #909399;
				font-size: 40rpx;
				padding: 10rpx;
			}
		}

		.popup-body {
			max-height: 60vh;
			overflow-y: auto;

			.checkbox-item,
			.radio-item {
				display: flex;
				align-items: center;
				padding: 24rpx 0;
				border-bottom: 2rpx solid #f5f7fa;

				&:last-child {
					border-bottom: none;
				}

				.checkbox-label,
				.radio-label {
					margin-left: 16rpx;
					font-size: 28rpx;
					color: #303133;
				}
			}
		}
	}

	.submit-btn {
		width: 100%;
		height: 96rpx;
		line-height: 96rpx;
		text-align: center;
		background-color: #2979ff;
		color: #fff;
		border-radius: 12rpx;
		font-size: 32rpx;
		margin-top: 60rpx;
		font-weight: 500;
		box-shadow: 0 4rpx 12rpx rgba(41, 121, 255, 0.2);
	}

	// 修复picker的样式
	::v-deep .uni-calendar {
		border-radius: 16rpx;
		overflow: hidden;
		box-shadow: 0 4rpx 12rpx rgba(0, 0, 0, 0.1);

		.uni-calendar__header {
			padding: 24rpx;
			background-color: #2979ff;

			.uni-calendar__header-text {
				font-size: 32rpx;
				color: #fff;
				font-weight: 500;
			}
		}

		.uni-calendar__body {
			padding: 24rpx;

			.uni-calendar-item__weeks-box {
				border-radius: 8rpx;

				&.uni-calendar-item--disable {
					opacity: 0.4;
				}

				&.uni-calendar-item--checked {
					background-color: #2979ff;

					.uni-calendar-item__weeks-text {
						color: #fff;
					}
				}
			}
		}
	}

	// 修复checkbox样式
	::v-deep .uni-checkbox-input {
		border-radius: 6rpx;

		&.uni-checkbox-input-checked {
			background-color: #2979ff !important;
			border-color: #2979ff !important;

			&::before {
				font-size: 24rpx;
			}
		}
	}

	// 修复radio样式
	::v-deep .uni-radio-input {
		&.uni-radio-input-checked {
			background-color: #2979ff !important;
			border-color: #2979ff !important;

			&::before {
				font-size: 24rpx;
			}
		}
	}

	.task-list {
		.task-item {
			display: flex;
			align-items: center;
			justify-content: space-between;
			padding: 24rpx 20rpx;
			border-bottom: 2rpx solid #f5f7fa;

			&:last-child {
				border-bottom: none;
			}

			&--selected {
				background-color: #eef6ff;
				border: 2rpx solid #007aff;

				.task-label {
					color: #2979ff;
					font-weight: 500;
				}
			}

			.task-label {
				font-size: 28rpx;
				color: #303133;
			}

			.selected-icon {
				color: #2979ff;
				font-size: 32rpx;
				font-weight: bold;
			}

			.task-list {
				.task-item {
					// ... 原有样式保持不变 ...

					&--disabled {
						opacity: 0.5;
						background-color: #f5f5f5;
						cursor: not-allowed;

						.task-label {
							color: #999;
						}
					}
				}
			}
		}
	}
</style>